package com.nihome.entershopinfo.fragments;

import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Html;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.nihome.entershopinfo.Constants;
import com.nihome.entershopinfo.R;
import com.nihome.entershopinfo.adapter.SysSpinnerAdapter;
import com.nihome.entershopinfo.application.SysApplication;
import com.nihome.entershopinfo.dialog.ImagePickDialog;
import com.nihome.entershopinfo.dialog.LoadingDialog;
import com.nihome.entershopinfo.entity.User;
import com.nihome.entershopinfo.entity.request.BasicInfoReq;
import com.nihome.entershopinfo.entity.request.UploadImgReq;
import com.nihome.entershopinfo.entity.response.ExpandsLogRes;
import com.nihome.entershopinfo.entity.response.ResponseBase;
import com.nihome.entershopinfo.entity.response.UploadImgRes;
import com.nihome.entershopinfo.ui.HomePageActivity;
import com.nihome.entershopinfo.ui.PermissionsActivity;
import com.nihome.entershopinfo.utils.Base64Util;
import com.nihome.entershopinfo.utils.BitmapUtils;
import com.nihome.entershopinfo.utils.ImagePicker;
import com.nihome.entershopinfo.utils.Log;
import com.nihome.entershopinfo.utils.NetUtil;
import com.nihome.entershopinfo.utils.PermissionsChecker;
import com.nihome.entershopinfo.utils.RequestAPI;
import com.nihome.entershopinfo.utils.StringUtils;
import com.squareup.picasso.Picasso;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.Callback;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.net.SocketException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;

import okhttp3.Call;
import okhttp3.MediaType;
import okhttp3.Response;

/**
 * Created by Carson on 2017/7/18.
 */
public class BasicInfoFragment extends Fragment implements View.OnClickListener, ImagePickDialog.DialogSelectedListener{
    private static final String TAG = "BasicInfoFragment";
    private Context mContext;
    private Gson mGson;
    private User mUser;
    private NetUtil mNetUtil;
    private LoadingDialog dialog;

    private int selectType;
    private ExpandsLogRes expandsLog;

    private BasicInfoReq basicInfoReq;
    private String auditId;
    private short operation;

    private String parentAuditId;

    private TextView basicInfoPrompt;
    private LinearLayout shopNameLayout;
    private EditText shopNameEdit;
    private EditText contactsNameEdit;
    private EditText contactsPhoneEdit;
    private ImageView businessPersonalImg;
    private ImageView businessCompanyImg;
    private LinearLayout businessTypeLayout;
    private LinearLayout businessPersonalLayout;
    private LinearLayout businessCompanyLayout;
    private ImageView radioTrueImg;
    private ImageView radioFalseImg;
    private LinearLayout restaurantTrueLayout;
    private LinearLayout restaurantFalseLayout;
    private TextView backBtn;
    private TextView goNextBtn;


    private LinearLayout childShopLayout;
    private Spinner joinTypeSpinner;
    private LinearLayout yesCashLayout;
    private ImageView yesCashImg;
    private LinearLayout noCashLayout;
    private ImageView noCashImg;


    private LinearLayout industryTypeLayout;

    private LinearLayout businessLicensePhotoLayout;
    private ImageView businessLicensePhoto;
    private String phoneUrl;

    private Short restaurantType = 1;
    private Short businessType = 1;

    private int joinInType = 0;
    private int ifCashType = 1;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mContext = getActivity();
        mGson = new Gson();
        mUser = SysApplication.getInstance().getmUser();
        mNetUtil = new NetUtil(mContext);
        dialog = new LoadingDialog(mContext);
        selectType = getArguments().getInt(Constants.SELECT_TYPE);
        expandsLog = getArguments().getParcelable(Constants.DATA);
        parentAuditId = getArguments().getString("parentAuditId");
        mPermissionsChecker = new PermissionsChecker(mContext);
        auditId = SysApplication.getInstance().getAuditId();
        if (expandsLog.getBasicInfoResponseDTO() == null) operation = Constants.NEW;
        else operation = Constants.UPDATE;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_basic_info, container, false);
        basicInfoPrompt = (TextView) view.findViewById(R.id.basic_info_prompt);
        shopNameLayout = (LinearLayout) view.findViewById(R.id.shop_name_layout);
        shopNameEdit = (EditText) view.findViewById(R.id.shop_name_edit);
        contactsNameEdit = (EditText) view.findViewById(R.id.contacts_name_edit);
        contactsPhoneEdit = (EditText) view.findViewById(R.id.contacts_phone_edit);
        businessPersonalImg = (ImageView) view.findViewById(R.id.business_personal_img);
        businessCompanyImg = (ImageView) view.findViewById(R.id.business_company_img);
        businessTypeLayout = (LinearLayout) view.findViewById(R.id.business_type_layout);
        businessPersonalLayout = (LinearLayout) view.findViewById(R.id.business_personal_layout);
        businessCompanyLayout = (LinearLayout) view.findViewById(R.id.business_company_layout);
        radioTrueImg = (ImageView) view.findViewById(R.id.radio_true_img);
        radioFalseImg = (ImageView) view.findViewById(R.id.radio_false_img);
        restaurantTrueLayout = (LinearLayout) view.findViewById(R.id.restaurant_true_layout);
        restaurantFalseLayout = (LinearLayout) view.findViewById(R.id.restaurant_false_layout);
        backBtn = (TextView) view.findViewById(R.id.basic_info_back);
        goNextBtn = (TextView) view.findViewById(R.id.basic_info_go_next);

        industryTypeLayout = (LinearLayout) view.findViewById(R.id.industry_type_layout);

        businessLicensePhotoLayout = (LinearLayout) view.findViewById(R.id.businessLicensePhoto_layout);
        businessLicensePhoto = (ImageView) view.findViewById(R.id.businessLicensePhoto);


        childShopLayout = (LinearLayout) view.findViewById(R.id.child_shop_layout);
        joinTypeSpinner = (Spinner) view.findViewById(R.id.join_type);
        yesCashLayout = (LinearLayout) view.findViewById(R.id.yes_cash_layout);
        yesCashImg = (ImageView) view.findViewById(R.id.yes_cash_img);
        noCashLayout = (LinearLayout) view.findViewById(R.id.no_cash_layout);
        noCashImg = (ImageView) view.findViewById(R.id.no_cash_img);

        hiddenView();
        setSpinner();

        basicInfoPrompt.setText(Html.fromHtml(getString(R.string.basic_info_prompt)));

        businessLicensePhoto.setOnClickListener(this);
        businessPersonalLayout.setOnClickListener(this);
        businessCompanyLayout.setOnClickListener(this);
        restaurantTrueLayout.setOnClickListener(this);
        restaurantFalseLayout.setOnClickListener(this);

        yesCashLayout.setOnClickListener(this);
        noCashLayout.setOnClickListener(this);

        backBtn.setOnClickListener(this);
        goNextBtn.setOnClickListener(this);
        if (operation == Constants.UPDATE) initData();

        return view;
    }


    private String[] joinType;
    private SysSpinnerAdapter joinTypeAdapter;
    private void setSpinner(){
        joinType = getResources().getStringArray(R.array.join_type);

        joinTypeAdapter = new SysSpinnerAdapter(mContext, joinType);
        joinTypeSpinner.setAdapter(joinTypeAdapter);
        joinTypeSpinner.setSelection(0, true);
        joinTypeSpinner.setOnItemSelectedListener(new SpinnerItemSelect());

    }


    class SpinnerItemSelect implements AdapterView.OnItemSelectedListener{
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            joinInType = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {

        }
    }


    private void hiddenView(){
        if (selectType == Constants.XCX_TYPE || selectType == Constants.CHAIN_TYPE) {
            businessLicensePhotoLayout.setVisibility(View.GONE);
            businessTypeLayout.setVisibility(View.VISIBLE);
            industryTypeLayout.setVisibility(View.VISIBLE);

            childShopLayout.setVisibility(View.GONE);
        }
        if (selectType == Constants.H5_TYPE) {
            businessLicensePhotoLayout.setVisibility(View.VISIBLE);
            businessTypeLayout.setVisibility(View.GONE);
            industryTypeLayout.setVisibility(View.VISIBLE);

            childShopLayout.setVisibility(View.GONE);
        }
        if (selectType == Constants.CHAIN_CHILD_TYPE) {
            businessLicensePhotoLayout.setVisibility(View.GONE);
            businessTypeLayout.setVisibility(View.VISIBLE);
            industryTypeLayout.setVisibility(View.VISIBLE);

            childShopLayout.setVisibility(View.VISIBLE);
        }
    }

    private void initData(){
        shopNameEdit.setText(expandsLog.getBasicInfoResponseDTO().getStoreName());
        contactsNameEdit.setText(expandsLog.getBasicInfoResponseDTO().getContactsName());
        contactsPhoneEdit.setText(expandsLog.getBasicInfoResponseDTO().getContactsMobile());
        joinTypeSpinner.setSelection(expandsLog.getBasicInfoResponseDTO().getPartnerType());
        if (selectType == Constants.XCX_TYPE || selectType == Constants.CHAIN_TYPE) {
            businessLicensePhotoLayout.setVisibility(View.GONE);
        }
        if (selectType == Constants.H5_TYPE) {
            businessLicensePhotoLayout.setVisibility(View.VISIBLE);
            if (StringUtils.isEmpty(expandsLog.getBasicInfoResponseDTO().getBusinessLicensePhoto())) {
                phoneUrl = "";
                businessLicensePhoto.setImageResource(R.drawable.upload_img);
            }else {
                phoneUrl = expandsLog.getBasicInfoResponseDTO().getBusinessLicensePhoto();
                Picasso.with(mContext).load(expandsLog.getBasicInfoResponseDTO().getBusinessLicensePhoto()).
                        placeholder(R.drawable.loading).resize(200, 200).into(businessLicensePhoto);
            }
        }
        if (selectType == Constants.CHAIN_CHILD_TYPE) {
            businessLicensePhotoLayout.setVisibility(View.GONE);
        }


        if (expandsLog.getBasicInfoResponseDTO().getStoreIndustry() == 1) {
            restaurantType = 1;
            radioTrueImg.setImageResource(R.drawable.radio_true);
            radioFalseImg.setImageResource(R.drawable.radio_false);
        }
        if (expandsLog.getBasicInfoResponseDTO().getStoreIndustry() == 2) {
            restaurantType = 2;
            radioFalseImg.setImageResource(R.drawable.radio_true);
            radioTrueImg.setImageResource(R.drawable.radio_false);
        }
        if (expandsLog.getBasicInfoResponseDTO().getBusinessLicenseType() == 1) {
            businessType = 1;
            businessPersonalImg.setImageResource(R.drawable.radio_true);
            businessCompanyImg.setImageResource(R.drawable.radio_false);
        }
        if (expandsLog.getBasicInfoResponseDTO().getBusinessLicenseType() == 2) {
            businessType = 2;
            businessCompanyImg.setImageResource(R.drawable.radio_true);
            businessPersonalImg.setImageResource(R.drawable.radio_false);
        }
    }

    void viewInit(){
        shopNameEdit.setText("");
        contactsNameEdit.setText("");
        contactsPhoneEdit.setText("");
        restaurantType = 1;
        businessType = 1;
        radioTrueImg.setImageResource(R.drawable.radio_true);
        radioFalseImg.setImageResource(R.drawable.radio_false);
        businessPersonalImg.setImageResource(R.drawable.radio_true);
        businessCompanyImg.setImageResource(R.drawable.radio_false);
        phoneUrl = "";
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            selectType = getArguments().getInt(Constants.SELECT_TYPE);
            expandsLog = getArguments().getParcelable(Constants.DATA);
            parentAuditId = getArguments().getString("parentAuditId");
            auditId = SysApplication.getInstance().getAuditId();
            if (expandsLog.getBasicInfoResponseDTO() == null) operation = Constants.NEW;
            else operation = Constants.UPDATE;
        }
        hiddenView();
        if (operation == Constants.NEW) viewInit();
        if (operation == Constants.UPDATE) initData();
    }





    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.businessLicensePhoto:
                showPhone();
                break;
            case R.id.business_personal_layout:
                businessType = 1;
                businessPersonalImg.setImageResource(R.drawable.radio_true);
                businessCompanyImg.setImageResource(R.drawable.radio_false);
                break;
            case R.id.business_company_layout:
                businessType = 2;
                businessCompanyImg.setImageResource(R.drawable.radio_true);
                businessPersonalImg.setImageResource(R.drawable.radio_false);
                break;
            case R.id.restaurant_true_layout:
                restaurantType = 1;
                radioTrueImg.setImageResource(R.drawable.radio_true);
                radioFalseImg.setImageResource(R.drawable.radio_false);
                break;
            case R.id.restaurant_false_layout:
                restaurantType = 2;
                radioFalseImg.setImageResource(R.drawable.radio_true);
                radioTrueImg.setImageResource(R.drawable.radio_false);
                break;
            case R.id.yes_cash_layout:
                ifCashType = 1;
                yesCashImg.setImageResource(R.drawable.radio_true);
                noCashImg.setImageResource(R.drawable.radio_false);
                break;
            case R.id.no_cash_layout:
                ifCashType = 0;
                yesCashImg.setImageResource(R.drawable.radio_false);
                noCashImg.setImageResource(R.drawable.radio_true);
                break;
            case R.id.basic_info_back:
                ((HomePageActivity)getActivity()).backClick();
                break;
            case R.id.basic_info_go_next:
                //((HomePageActivity)getActivity()).goNextOfBasicInfo();
                if (!mNetUtil.isNetConnected()) {
                    Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (check()) submitBasicInfo();
                else Toast.makeText(mContext, getString(R.string.submit_prompt), Toast.LENGTH_SHORT).show();
                break;
        }
    }


    private Boolean check(){
        if (StringUtils.isEmpty(shopNameEdit.getText().toString())) return false;
        if (StringUtils.isEmpty(contactsNameEdit.getText().toString())) return false;
        if (StringUtils.isEmpty(contactsPhoneEdit.getText().toString())) return false;
        return true;
    }


    private void submitBasicInfo(){
        dialog.show(getString(R.string.load_text));
        basicInfoReq = new BasicInfoReq();
        basicInfoReq.setAuditId(auditId);
        basicInfoReq.setMarketerId(mUser.getUserId());
        basicInfoReq.setOperation(operation);
        basicInfoReq.setStoreName(shopNameEdit.getText().toString());
        basicInfoReq.setStoreIndustry(restaurantType);
        basicInfoReq.setBusinessLicenseType(businessType);
        basicInfoReq.setPartnerType(joinInType);

        if (selectType == Constants.H5_TYPE) {
            if (!StringUtils.isEmpty(phoneUrl)) basicInfoReq.setBusinessLicensePhoto(phoneUrl);
        }
        if (selectType == Constants.CHAIN_CHILD_TYPE) {
            basicInfoReq.setParentAuditId(parentAuditId);

            basicInfoReq.setSubStoreCashType(ifCashType);
        }



        basicInfoReq.setContactsName(contactsNameEdit.getText().toString());
        basicInfoReq.setContactsMobile(contactsPhoneEdit.getText().toString());



        Log.e(TAG, "submitBasicInfo json = " + mGson.toJson(basicInfoReq));
        OkHttpUtils.postString().url(RequestAPI.BASIC_INFO_URL)
                .content(mGson.toJson(basicInfoReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new BasicInfoCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e + "");
                dialog.dismiss();
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<String> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        expandsLog.setBasicInfoResponseDTO(basicInfoReq);
                        if (selectType == Constants.XCX_TYPE || selectType == Constants.H5_TYPE || selectType == Constants.CHAIN_CHILD_TYPE) {
                            ((HomePageActivity)getActivity()).goNextOfBasicInfo();
                        }
                        if (selectType == Constants.CHAIN_TYPE) {
                            ((HomePageActivity)getActivity()).goNextOfBasicInfo();
                        }
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class BasicInfoCallback extends Callback<ResponseBase<String>> {
        @Override
        public ResponseBase<String> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<String>>(){}.getType();
            ResponseBase<String> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }


    private PermissionsChecker mPermissionsChecker; // 权限检测器
    static final String[] PERMISSIONS = new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.CAMERA};
    private static final int REQUEST_PERMISSION = 100;  //权限请求
    private ImagePickDialog imagePickDialog;
    private ImagePicker mImagePicker;
    private Uri cameraUri;
    private Uri cutImgUri;


    void showPhone(){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (mPermissionsChecker.lacksPermissions(PERMISSIONS)) {
                startPermissionsActivity();
            } else {
                showDialog();
            }
        } else {
            showDialog();
        }
    }

    private void showDialog(){
        if (imagePickDialog == null) imagePickDialog = new ImagePickDialog(mContext);
        imagePickDialog.setDialogSelectedListener(this);
        imagePickDialog.show();
    }

    @Override
    public void onPhone() {
        Log.e(TAG, "相册........");
        if (mImagePicker == null) mImagePicker = new ImagePicker(getActivity(), this);
        mImagePicker.pickOnphone();
    }

    @Override
    public void onCapture() {
        Log.e(TAG, "拍照........");
        if (mImagePicker == null) mImagePicker = new ImagePicker(getActivity(), this);
        cameraUri = mImagePicker.openCamera();
    }

    @Override
    public void onCancel() {

    }



    private void startPermissionsActivity() {
        PermissionsActivity.startActivityForResult(getActivity(), REQUEST_PERMISSION,
                PERMISSIONS);
    }

    /** 上传图片 */
    private void uploadImgService(){
        dialog.show(getString(R.string.load_text));
        Log.e(TAG, "image path = " + cutImgUri.getPath());
        String img = "data:image/png;base64,";
        img +=  Base64Util.encode(BitmapUtils.FileTobyte(new File(cutImgUri.getPath())));
        UploadImgReq uploadImgReq = new UploadImgReq();
        uploadImgReq.setFileBase64Data(img);
        uploadImgReq.setUserId(mUser.getUserId());
        OkHttpUtils.postString().url(RequestAPI.UPLOAD_IMG_URL)
                .content(new Gson().toJson(uploadImgReq))
                .mediaType(MediaType.parse("application/json; charset=utf-8"))
                .build().execute(new UploadImgCallback() {
            @Override
            public void onError(Call call, Exception e, int id) {
                Log.e(TAG, e + "");
                dialog.dismiss();
                if (e instanceof UnknownHostException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof SocketTimeoutException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }
                if (e instanceof IOException) {
                    Toast.makeText(mContext, getString(R.string.net_error), Toast.LENGTH_SHORT).show();
                    return;
                }

                Toast.makeText(mContext, getString(R.string.service_error), Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onResponse(ResponseBase<UploadImgRes> response, int id) {
                dialog.dismiss();
                switch (Integer.valueOf(response.getResultCode())) {
                    case Constants.REQ_SUCCESS:
                        Toast.makeText(mContext, getString(R.string.upload_success), Toast.LENGTH_SHORT).show();
                        phoneUrl = response.getResult().getFileUrl();
                        Picasso.with(mContext).load(response.getResult().getFileUrl()).
                                placeholder(R.drawable.loading).resize(200, 200).into(businessLicensePhoto);
                        break;
                    default:
                        Toast.makeText(mContext, response.getMsg(), Toast.LENGTH_SHORT).show();
                        break;
                }
            }
        });
    }

    abstract class UploadImgCallback extends Callback<ResponseBase<UploadImgRes>> {
        @Override
        public ResponseBase<UploadImgRes> parseNetworkResponse(Response response, int id) throws Exception {
            String string = response.body().string();
            Log.e(TAG, string);
            Type jsonType = new TypeToken<ResponseBase<UploadImgRes>>(){}.getType();
            ResponseBase<UploadImgRes> res = mGson.fromJson(string, jsonType);
            return res;
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == Activity.RESULT_OK) {
            switch (requestCode) {
                case ImagePicker.REQUEST_CAPTURE:
                    cutImgUri = mImagePicker.cropPhoto(cameraUri);
                    break;
                case ImagePicker.REQUEST_PICK_IMAGE:
                    cameraUri = data.getData(); //获取系统返回的照片的Uri
                    cutImgUri = mImagePicker.cropPhoto(cameraUri);
                    break;
                case ImagePicker.REQUEST_PICTURE_CUT:
                    if (!mNetUtil.isNetConnected()) {
                        Toast.makeText(mContext, getString(R.string.cannot_connect_network), Toast.LENGTH_SHORT).show();
                        return;
                    }
                    uploadImgService();
                    break;
            }
        }
    }
}
